<?php

namespace App\Service\Index\v1_2_7;

use App\Helpers\AliyunUtil;
use App\Model\Gift;
use App\Model\GiftLog;
use App\Model\UserProfile;
use App\Service\BaseService;

/**
 * 电视墙
 */
class TvWallService extends BaseService
{
    public function handle()
    {
        $from = $this->request->input('from', 0);
        $ret['list'] = $this->getGiftList(30);
        $ret['rules'] = '';
        // '如何上电视墙
        // 1、单次赠送礼物大于等于100金币，将根据最新的送礼时间上电视。
        // 2、当日赠送金额大于等于100金币且金额最高的土豪，将在礼物电视墙霸屏一日。';
        return $ret;
    }

    function getGiftList($num = 30)
    {
        $where = [
            ['gift_coin', '>=', 100],
        ];
        $exludeUids = explode(',', env('TV_WALL_EXUIDS', ''));
        $logs = GiftLog::where($where)->whereNotIn('user_id', $exludeUids)->orderBy('id', 'desc')->limit($num)->get()->toArray();
        $list = [];
        //礼物ID
        $giftIds = array_unique(array_column($logs, 'gift_id'));
        $giftInfo = Gift::getBatchInfo($giftIds);
        //赠送方ID
        $userIds = array_merge(array_column($logs, 'user_id'), array_column($logs, 'receive_user_id'));
        $userIds = array_diff($userIds, explode(',', env('TV_WALL_EXUIDS', '')));
        $profiles = UserProfile::getUsersProfile($userIds, true);
        foreach ($logs as $log) {
            $giftItem = $giftInfo[$log['gift_id']];
            $receiver = $profiles[$log['receive_user_id']];
            if ($receiver['gender'] == 1) $receiverName = $receiver['nick_name'];
            else $receiverName = "神秘美女";
            $list[] = [
                'sender_name' => $profiles[$log['user_id']]['nick_name'], //'****' . mb_substr($profiles[$log['user_id']]['nick_name'], -1),
                'receiver_name' => $receiverName, //"ID5****" . mb_substr($receiver, -1),
                'gift_name' => $giftItem['name'],
                'gift_coin' => "💗💗💗", //$giftItem['coin'] . "金币",
                'coin' => $giftItem['coin'],
                'gift_icon' => AliyunUtil::IMG_HOST_V2 . $giftItem['icon'],
                'sender_avatar' => UserProfile::buildAvatar($profiles[$log['user_id']]['avatar'], 150),
                'top' => 0,
                'show_gift_coin' => 0,
            ];
        }
        if ($list) {
            array_multisort(array_column($list, 'coin'), SORT_DESC, $list);
            $list[0]['top'] = 1;
        }
        return $list;
    }
}
